<template>
  <!--#f0f3f8-->
  <div >
   <div class="cart" >
     <el-card class="box-card">
       <div slot="header" class="clearfix">
         <h3>我的购物车</h3>
       </div>
    <div class="core">
      <!--<el-divider></el-divider>-->
      <!--  -->
      <el-table
          :header-cell-style="{ 'text-align': 'center' }"
          ref="multipleTable"
          :data="cartList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="商品" width="300" align="left">
          <template slot-scope="scope">
            <div class="goods">
              <img
                  :src="scope.row.productImgUrl"
                  alt="商品"
                  class="pointer"
                  width="120px"
                  height="120px"
              />
              <span v-text="scope.row.productName"> </span>
            </div>
          </template>
        </el-table-column>
        <!-- 轮播图预处理 标题 价格 num   -->
        <el-table-column align="center" prop="productPrice" label="单价" width="120">
        </el-table-column>
        <el-table-column
            align="center"
            prop="productCount"
            label="数量"
            show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-input-number
                size="small"
                :min="0"
                :max="scope.row.productStock"
                @change="numberChange(scope.row.productId, scope.row.productCount)"
                v-model="scope.row.productCount"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="小计" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>
              <span style="font-size: 12px"> ¥ </span>
              <!--{{ totalAmount(scope.$index) }}-->
              {{ scope.row.total | rounding }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row.productId)"
            >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px" class="bottom">
        <div>
          <el-button @click="selectAll(cartList)">全选</el-button>
          <el-button @click="toggleSelection()">清空</el-button>
        </div>

        <div class="value">
          <div class="total inline-block">
            <span>总价：</span>
            <span> ¥ </span>
            <span class="money">{{ totalAmount().toFixed(2)  }}</span>
          </div>
          <el-button @click="toPay()" type="primary" plain>
            立即购买
          </el-button>
        </div>
      </div>
    </div>
     </el-card>
  </div>
  </div>
</template>

<script>
import {getToken, getUser} from '../../utils/baseinfo';
import {getCart, deleteCart, updateCart} from '../../api/user/cart';
import computed from "@vue/composition-api";

export default {
  name: 'Cart',

  computed: {

  },

  filters: {
    rounding(value) {
      return value.toFixed(2);
    }
  },

  data() {
    return {
      cartList: [],
      page: 1,
      size: 10,
      // tableData: this.$store.state.userInfo.carts,
      multipleSelection: [],
      isMounted: false,
      val: []
    };
  },

  created() {
    if(this.checkLogin()) {
      this.init();
    }
  },

  methods: {
    checkLogin() {
      const token = getToken();
      if(token == undefined || token == '') {
        this.$message.error("未登录，请登录")
        this.$router.push({path: '/'});
        return false;
      }
      return true;
    },
    init() {
      const userId = getUser() != null ? getUser().id : '';
      console.log("userID")
      console.log(userId)
      getCart(userId, this.page, this.size).then(response => {
        this.cartList = response.data.carts
        console.log("购物车")
        console.log(this.cartList)
      }).catch(error => {
        this.$message.error(error)
      })
    },

    numberChange(productId, count){
      console.log("productId")
      console.log(productId)
      const userId = getUser() != null ? getUser().id : '';
      const cartId = this.cartList[0].cartId;
      this.cartList.map((item,index)=>{
        if(productId === item.productId){
          item.total = item.productCount * item.productPrice;
          console.log(item.productCount * item.productPrice)
        }
      })
      // 更新购物车的数据
      updateCart(userId, cartId, productId, count).then(response => {
        console.log("cart 更新数据成功")
      }).catch(error => {
        this.$message.error(error)
        this.init();
      })
    },

    handleDelete(productId){
      const userId = getUser() != null ? getUser().id : '';
      const cartId = this.cartList[0].cartId;

      deleteCart(userId, cartId, productId).then(()=>{
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.cartList.map((item,index)=>{
          if(item.productId === productId){
            this.cartList.splice(index,1);
          }
        })
      }).catch((error)=>{
            this.$message({
              message: error,
              type: 'error'
            })
          })
    },

    toPay() {
      let arr = this.$refs.multipleTable.selection;
      if (arr.length <= 0) {
        // 购物车无商品，支付失败
        this.$message({
          type: 'warning',
          message: '请先选择商品!',
        });
      } else {
        console.log("arr")
        console.log(arr);
        this.$router.push({
          name: 'pay',
          path: '/pay',
          params: {
            data: arr,
          },
          query: {
            cartId: this.cartList.length > 0 ? this.cartList[0].cartId : '',
          },
        });
      }
    },

    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    handleSelectionChange(val) {
      console.log("多选框被选中")
      console.log(val)
      this.val = val;
      this.multipleSelection = val;

    },

    totalAmount() {
      let amount = 0;
      this.val.forEach( item => {
        amount += item.productCount * item.productPrice;
      })
      return amount;
    },

    selectAll(rows) {
      console.log('全选按钮被点击了');
      this.$refs.multipleTable.clearSelection();
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      }
    },
  }
};
</script>

<style scoped>
.cart {
  width: 1000px;
  /*width: 100%;*/
  margin-bottom: 40px;
  margin-left: auto ;
  margin-right: auto;
  /*margin: 40px auto;*/
  padding: 10px 20px;
  background: #fff;

}

.goods {
  display: flex;
  align-items: center;
}

.cart .bottom {
  display: flex;
  justify-content: space-between;
}

.cart .bottom .value {
  display: flex;
  align-items: center;
}
.cart .bottom .value {
  color: #666;
  font-size: 14px;
  padding: 0 10px;
}

.cart .bottom .value .total {
  margin: 0 8px;
}

.cart .bottom .value .money {
  font-size: 18px;
}
</style>
